import vm from '@/main'

import axios from 'axios'
import Cache from '@/utils/cache/index'
let cache = new Cache()
import constant from '@/utils/constant'
let { CACHE_LOGIN_TOKEN, CACHE_USER_INFO, CACHE_AUTH_LIST } = constant

let { VUE_APP_baseURL } = process.env

// 创建axios实例
const http = axios.create({
    baseURL: VUE_APP_baseURL, // API 请求的默认前缀
    timeout: 30000 // 请求超时时间
})

const handleMethod = {
    get (config) {
        // 过滤掉没用的属性
        let params = {}
        for (let key in config.params) {
            config.params[key] && (params[key] = config.params[key])
        }
        config.params = params


        return config
    },
    post (config) {
        console.log(config)
        return config
    },
}

// 处理不同状态码
const handleStatus = {
    401 () { // 未登录或者登录过期
        console.log(CACHE_LOGIN_TOKEN)
        cache.removeCache(CACHE_LOGIN_TOKEN, () => {
            vm.$router.push({
                name: 'login',
            })
        })

    }
}

// 请求拦截器
http.interceptors.request.use(config => {
    let { method } = config

    let token = cache.getCache(CACHE_LOGIN_TOKEN)

    if (token) config.headers.Authorization = `Bearer ${token}`

    config = handleMethod[method.toLowerCase()](config)
    // console.log(handleMethodFn)
    // handleMethodFn()

    return config
})

// 响应拦截器
http.interceptors.response.use(response => {
    let { status } = response.data
    console.log(status)
    // 处理不同状态码
    handleStatus[status] && handleStatus[status]()


    return response.data
})

export default http
